package com.zhuqiao.tm.transactional;

import com.alibaba.fastjson.JSONObject;
import com.zhuqiao.tm.netty.NettyClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class MyTransactionManager {
    private static NettyClient nettyClient;
    private static Map<String, MyTransaction> transactionMap = new HashMap<>();
    private static ThreadLocal<MyTransaction> transactionThreadLocal = new ThreadLocal<>();
    private static ThreadLocal<String> groupIdThreadLocal = new ThreadLocal<>();
    private static String transactionCount;


    public static void setTransactionCount(String total) {
        transactionCount = total;
    }

    public static String getTransactionCount() {
        return transactionCount;
    }


    @Autowired
    public void setNettyClient(NettyClient nettyClient) {
        MyTransactionManager.nettyClient = nettyClient;
    }

    //创建事务组，提交事务组
    public static String createTransactionGroup() {
        String groupId = UUID.randomUUID().toString();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("groupId", groupId);
        jsonObject.put("command", "create");
        nettyClient.send(jsonObject);
        groupIdThreadLocal.set(groupId);
        return groupId;
    }

    //创建事务
    public static MyTransaction createTransaction(String groupId) {
        String transactionId = UUID.randomUUID().toString();
        MyTransaction myTransaction = new MyTransaction(groupId, transactionId);
        transactionMap.put(groupId, myTransaction);
        transactionThreadLocal.set(myTransaction);
        return myTransaction;
    }

    //添加事务到事务组
    public static MyTransaction addTransaction(MyTransaction myTransaction, Boolean isEnd) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("groupId", myTransaction.getGroupId());
        jsonObject.put("transactionId", myTransaction.getTransactionId());
        jsonObject.put("transactionType", myTransaction.getTransactionType());
        jsonObject.put("command", "add");
        jsonObject.put("isEnd", isEnd);
        jsonObject.put("transactionCount", MyTransactionManager.getTransactionCount());

        nettyClient.send(jsonObject);
        return myTransaction;
    }

    public static MyTransaction getTransactionByGroupId(String groupId) {
        return transactionMap.get(groupId);
    }

    public static MyTransaction getCurrentTransaction() {
        return transactionThreadLocal.get();
    }

    public static void setCurrentGroupId(String groupId) {
        groupIdThreadLocal.set(groupId);
    }

    public static String getCurrentGroupId() {
        return groupIdThreadLocal.get();
    }

}
